<template>
    <!-- A4 纸 预览 -->
    <div ref="renderPaper" :class="['render-paper-a4', { layoutRow: element.options.layout === 'row' }]"
        :style="{
            'padding-top': `${element.options.paddingTop}mm`,
            'padding-bottom': `${element.options.paddingBottom}mm`,
            'padding-left': `${element.options.paddingLeft}mm`,
            'padding-right': `${element.options.paddingRight}mm`
        }">
        <div class="paper">
            <div v-for="(el, paperIndex) in element.elementItems" :key="paperIndex" class="paper-item" :style="{
                'display': `${el.options.display ? el.options.display : 'initial' }`
            }">
                <RenderLayout v-if="el && el.type === 'layout'" :element="el" :Api="Api" @tableDataPage="tableDataPage" @hidePage="hidePage" :apiIndex="element.apiIndex || 0" :reportData="reportData" :index="index"></RenderLayout>
                <RenderBase v-else-if="el && el.type === 'base'" :element="el" :Api="Api" :apiIndex="element.apiIndex || 0" :reportData="reportData" :index="index"></RenderBase> 
            </div>
        </div>
        <!-- 页码 -->
        <div v-show="element.options.isPage" :class="['A4-page', { right: element.options.pagePosition === 'right' }]">
            — {{ index + 1 }} —
        </div>
        <div class="render-paper-action" v-if="reportData.previewOption.mode == 'edit'">
            <el-button-group>
                <el-tooltip effect="dark" content="复制" placement="top">
                    <el-button type="primary" icon="el-icon-copy-document" @click.stop="copyPaper()"></el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="删除" placement="top" v-if="index != 0">
                    <el-button type="primary" icon="el-icon-delete" @click.stop="deletePaper()"></el-button>
                </el-tooltip>
            </el-button-group>
        </div>
    </div>
</template>

<script>
import RenderLayout from "../RenderLayout/RenderLayout";
import RenderBase from "../RenderBase/RenderBase.vue";
import Watermark from "../../../../utils/watermark";
import * as _ from 'lodash';
import { warning, success, errorInfo } from "@/utils/errorInfo";
export default {
    name: "RenderPaper",
    props: {
        element: {
            type: Object
        },
        index: {
            type: Number
        },
        Api: {
            type: Object
        },
        reportData: {
            type: Object
        }
    },
    components: {
        RenderLayout,
        RenderBase
    },
    methods: {
        tableDataPage() { // 处理TableData数据分页
            let data = _.cloneDeep(this.reportData.elementItems[this.index]);
            this.reportData.elementItems.splice(this.index + 1, 0, {
                label: "A4纸", // 组件label
                type: "paper_A4", // 类型
                icon: "el-icon-tickets", // 图标
                designComponentName: "DesignPaper", // 配置编辑组件命名
                propComponentName: "PropParperA4", // 配置属性组件命名
                renderComponentName: "RenderPaper", // 配置预览、渲染、打印组件
                options: data.options,
                elementItems: []
            });
            this.$nextTick(() => {
                let newReportData = this.reportData.elementItems[this.index + 1];
                newReportData.elementItems = [...data.elementItems];
            });
        },
        handlePage() { // 处理内容超出择进行分页
            this.$nextTick(() => {
                let dom = this.$refs.renderPaper || null;
                let paperItem = dom && dom.querySelectorAll('.paper-item') || [];
                let domPaddingTop = dom && dom.style.paddingTop.slice(0, -2);
                let nextPage = []; // 下一页数据的下标
                paperItem.forEach((item, index) => {
                    // (Number(domPaddingTop) * 3.8) 是 MM * 3.8 = px 
                    // 20 则是底部预留空白20PX
                    if ((item.offsetTop + item.offsetHeight + (Number(domPaddingTop) * 3.8) + 20) > dom.offsetHeight) {
                        nextPage.push(index);
                    }
                })
                // 数据渲染
                if (nextPage && nextPage.length > 0) { // 需要进行分页
                    const pageData = this.element.elementItems.filter((item, index) => {
                        return index >= nextPage[0];
                    });
                    const currentPageData = this.element.elementItems.filter((item, index) => {
                        return index < nextPage[0];
                    })
                    this.element.elementItems = currentPageData;
                    if (this.reportData.elementItems[this.index + 1]) { // 有第二页
                        // 渲染第二页：
                        const page = {
                            ...this.reportData.elementItems[this.index + 1],
                            elementItems: [...pageData, ...this.reportData.elementItems[this.index + 1].elementItems]
                        }
                        this.reportData.elementItems.splice(this.index + 1, 1);
                        let time = setTimeout(() => {
                            this.reportData.elementItems.splice(this.index + 1, 0, page);
                            clearTimeout(time);
                            time = null;
                        }, 200);
                    } else { // 无第二页
                        if (this.reportData.elementItems.length < 10) {
                            const page = {
                                ...this.reportData.elementItems[this.index],
                                elementItems: pageData
                            }
                            this.reportData.elementItems.push(page);
                        } else {
                            errorInfo('检测到报表数据正在无限添加，请减少字数后操作或预览');
                        }
                    }
                }
            })
        },
        hidePage() { // table 组件 无数据时 进行隐藏当前页面
            this.$nextTick(() => {
                this.reportData.elementItems.splice(this.index, 1);
            })
        },
        pageWatermark() { // 水印功能
            let dom = this.$refs.renderPaper;
            this.Watermark = new Watermark(dom, {
                watermark_width: 110,
                watermark_font: 'fs_gb2312'
            });
            this.Watermark.setWatermark();
        },
        dataShow() {
            let field = this.element.options.dataShowField && this.element.options.dataShowField.split(',');
            if (field && field.length > 0) { // 开启无值隐藏，并且绑定相关字段
                let isShow = field.every((item) => {
                    let keyVal = item.split(':');
                    let value = this.Api.options[Number(keyVal[0])]?.data?.[keyVal[1]] || null;
                    return value && value.length > 0;
                })
                !isShow && this.hidePage();
            }
        },
        copyPaper() {
            this.$emit('copyPaper', this.index);
        },
        deletePaper() {
            this.$emit('deletePaper', this.index);
        }
    },
    mounted() {
        this.$nextTick(() => {
            // 水印功能
            if (this.element.options.watermark) this.pageWatermark();
            // 自动分页（仅为正常渲染时可进行分页）
            if (this.reportData.reportOption.reportRenderingType === 'normal') {
                let time = setTimeout(() => {
                    this.handlePage(); // 自动分页
                    clearTimeout(time);
                    time = null;
                }, 200);
            }
            // A4纸无值隐藏
            this.element.options.dataShow && this.dataShow();
        })
    }
}
</script>
